﻿using BLL;
using Model;
using NCRE学生考试端V1._0.PPT操作题类;
//using NCRE学生考试端V1._0.Word操作题类;
using System;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.Text.RegularExpressions;
using System.IO;

namespace NCRE学生考试端V1._0.判分操作类
{
    public partial class FrmJudge : Form
    {
        private static int SelectNum = 0;
        private static int WordNum = 0;
        private static int PptNum = 0;
        private static int WinNum = 0;
        private static int ExcelNum = 0;
        private static int IENum = 0;
        /// <summary>
        /// 用于进度条
        /// </summary>
        BackgroundWorker worker;
        /// <summary>
        /// 错误日志
        /// </summary>
        private LogEntity logInfo = new LogEntity();
        private static Form frmjudge;

        public FrmJudge()
        {
            InitializeComponent();
            worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            frmjudge = this;
        }

        #region 异步判分
        /// <summary> 
        /// 异步判分
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                //用于计算执行的操作             
                Kill();

                string TimeTamp = MyInfo.TimeTamp();
                string studentID = MyInfo.MystudentID();
                #region 初始化logInfo属性 2018年3月31日
                logInfo.timeSpan = TimeTamp;
                logInfo.studentId = studentID;
                logInfo.pagerType = MyInfo.MyPaperType();
                logInfo.errerInfo = string.Empty;
                logInfo.excelInfo = string.Empty;
                logInfo.ieInfo = string.Empty;
                logInfo.pptInfo = string.Empty;
                logInfo.sumErrerInfo = string.Empty;
                logInfo.uploadInfo = string.Empty;
                logInfo.wordInfo = string.Empty;
                logInfo.winInfo = string.Empty;
                logInfo.userIp = MyInfo.GetInternalIP();
                #endregion

                #region 进行评分操作 2015年12月14日13:52:43-李少然-卢彦聪改为多线程判分-2018-5-1
                #region 多线程异步判分
                Thread wordthread = new Thread(WordThread);
                wordthread.Start();

                Thread winthread = new Thread(WinThread);
                winthread.Start();

                Thread excelthread = new Thread(ExcelThread);
                excelthread.Start();

                Thread pptthread = new Thread(PptThread);
                pptthread.Start();

                Thread iethread = new Thread(IEThread);
                iethread.Start();

                Thread selectthread = new Thread(SelectThread);
                selectthread.Start();

                wordthread.Join();
                winthread.Join();
                excelthread.Join();
                pptthread.Join();
                iethread.Join();
                selectthread.Join();
                #endregion

                if (WordNum == 0)
                {
                    wordthread.Abort();
                }
                if (WinNum == 0)
                {
                    winthread.Abort();
                }
                if (ExcelNum == 0)
                {
                    excelthread.Abort();
                }
                if (PptNum == 0)
                {
                    pptthread.Abort();
                }
                if (IENum == 0)
                {
                    iethread.Abort();
                }
                if (SelectNum == 0)
                {
                    selectthread.Abort();
                }

                Kill();

                #region 分数汇总 修改人：白爱民-修改分数汇总条件-2018年12月23日
                //查询绑定表中的考试模式
                StudentBindPaperTypeBLL studentBindPaperBll = new StudentBindPaperTypeBLL();
                DataTable dt = studentBindPaperBll.SelectByStudentID(studentID);
                string ExamModel = dt.Rows[0]["ExamModel"].ToString();

               


                try
                {
                    //如果上边的excel等判分完成了，就进行分数的汇总                    
                    //if ((WordNum + WinNum + ExcelNum + PptNum + IENum + SelectNum) ==6)
                    //{
                    //    //计算一个学生一套试卷的总分-李芬-2015年11月30日
                    //    TypeSumFrationBll typesumfration = new TypeSumFrationBll();
                    //    typesumfration.SumFration(studentID, TimeTamp, ExamModel);
                    //}

                    if ((WordNum + WinNum + ExcelNum + PptNum + IENum + SelectNum) >0)
                    {
                        //计算一个学生一套试卷的总分-李芬-2015年11月30日
                        TypeSumFrationBll typesumfration = new TypeSumFrationBll();
                        typesumfration.SumFration(studentID, TimeTamp, ExamModel);


                        
                    }
                }
                catch (Exception em)
                {
                    //MessageBox.Show("分数汇总错误")
                    logInfo.sumErrerInfo += "分数汇总错误" + em.Message;
                }
                #endregion

                #endregion
            }
            catch (Exception eme)
            {
                logInfo.errerInfo = "交卷失败" + eme.Message;
                CheckForIllegalCrossThreadCalls = false;
                frmjudge.Close();
                Environment.Exit(0);
            }

            //考试模式下不更新到数据库——薛帅行——2018年12月29号15点10分
            DataTable dt3 = new LogBll().QuerySetUpBll();
            if (dt3.Rows[0]["is_upload"].ToString() != "0")   //根据是否有提示框来判断，因为is_exam没有地方修改过，一直为1  //练习模式
            {
                #region 将考生数据存到数据库中——薛帅行——2018年12月25号16点49分

                //float sumFration = float.Parse(Excelsumfration) + float.Parse(IEsumfration) + float.Parse(pptsumfration) + float.Parse(selectsumfration) + float.Parse(winsumfration) + float.Parse(wordsumfration);
                ScoreEntity score1 = new ScoreEntity();
            score1.studentID = FrmLogin.studentID;
            TypeSumFrationBll typesumfration1 = new TypeSumFrationBll();
            DataTable dt1 = typesumfration1.inquiryScore(score1);

            ScoreAdornEntity score = new ScoreAdornEntity();
            score.userId = LoginEntity.studentID;
            score.userName = LoginEntity.studentName;
            score.userCode = FrmLogin.studentID;   //学号登陆怎么判断
            score.totalScore = Convert.ToSingle(dt1.Rows[0]["score"]);
            score.multipleChoeceRanking = Convert.ToString(dt1.Rows[0]["SelectScore"]);
            score.WordRanking = Convert.ToString(dt1.Rows[0]["WordScore"]);
            score.ExcelRanking = Convert.ToString(dt1.Rows[0]["ExcelScore"]);
            score.IERanking = Convert.ToString(dt1.Rows[0]["IEScore"]);
            score.WindowsRanking = Convert.ToString(dt1.Rows[0]["WinScore"]);
            score.PPTRanking = Convert.ToString(dt1.Rows[0]["PPTScore"]);
            score.loginTime = Convert.ToDateTime(dt1.Rows[0]["timeSpan"]);
            score.is_Input = "1";

            TypeSumFrationBll addScoreAdorn = new TypeSumFrationBll();
            addScoreAdorn.addScoreAdorn(score);
                #endregion
            }
        }
        #endregion

        #region 多线程需要执行的各个方法
        private void SelectThread()
        {
            TypeSumFrationBll typesumfration = new TypeSumFrationBll();
            string TimeTamp = MyInfo.TimeTamp();
            string studentID = MyInfo.MystudentID();
            //计算选择题型的总分—李芬-2015年11月30日
            typesumfration.SelectsumFration(studentID, TimeTamp);
            SelectNum = 1;
        }

        private void WordThread()
        {
            #region Word判分  2015年11月23日
            try
            {
                TypeSumFrationBll typesumfration = new TypeSumFrationBll();
                string TimeTamp = MyInfo.TimeTamp();
                string studentID = MyInfo.MystudentID();

                //TODO:word判分
                WordQuestionRecordEntity student = new WordQuestionRecordEntity();
                WordQuestionEntityBll wordquestionbll = new WordQuestionEntityBll();
                WordQuestionEntity wordinfo = new WordQuestionEntity();


                //根据试卷类型查找题库中的题，然后对这些题根据flag进行判分
                string PaperType;
                PaperType = MyInfo.MyPaperType();
                //下面的dt表示按照试卷类型在数据库中加载word的题目信息
                DataTable dt = wordquestionbll.LoadWordByPaperType(PaperType);
                //得到学生答题的学生号
                student.StudentID = MyInfo.MystudentID();
                //word判分                    
                JudgeWord(PaperType, student, wordquestionbll, wordinfo, dt);
                //计算word总分                         
                typesumfration.WordSumFration(studentID, TimeTamp);
                WordNum = 1;
            }
            catch (Exception em)
            {
                logInfo.wordInfo = "word判分: " + em.Message;
            }
            #endregion
        }

        private void PptThread()
        {
            #region ppt判分
            try
            {
                TypeSumFrationBll typesumfration = new TypeSumFrationBll();
                string TimeTamp = MyInfo.TimeTamp();
                string studentID = MyInfo.MystudentID();
                PptJudgeHelper Pptjudge = new PptJudgeHelper();
                Pptjudge.PptJudgebyQuestionFlag();
                //计算PPT题型总分-王荣晓-2015年11月30日
                typesumfration.PPTSumFration(studentID, TimeTamp);
                PptNum = 1;
            }
            catch (Exception em)
            {
                logInfo.pptInfo = "ppt错误：" + em.Message;
            }
            #endregion
        }

        private void WinThread()
        {
            #region Windows判分 2015年11月23日

            try
            {
                TypeSumFrationBll typesumfration = new TypeSumFrationBll();
                string TimeTamp = MyInfo.TimeTamp();
                string studentID = MyInfo.MystudentID();
                WinQuestionEntity wininfo = new WinQuestionEntity();
                wininfo.paperType = MyInfo.MyPaperType();

                WindowsQuestionFlag windowsQuestionFlag = new WindowsQuestionFlag();
                windowsQuestionFlag.SwitchQuestionFlag(wininfo);
                WinQuestionEntityBll winquestion = new WinQuestionEntityBll();
                WinQuestionRecordEntity winrecored = new WinQuestionRecordEntity();
                winrecored.studentID = MyInfo.MystudentID();

                //启动一个新线程，用于windows判分
                winquestion.ReturnScore(WindowsLoadInfo.list, winrecored);

                //计算windows题型总分-王荣晓-2015年11月30日
                typesumfration.windowsSumFration(studentID, TimeTamp);
                WinNum = 1;
            }
            catch (Exception em)
            {
                //MessageBox.Show("windows错误")
                logInfo.winInfo = "windows错误" + em.Message;
            }
            #endregion
        }

        private void IEThread()
        {
            #region IE判分 2015年11月23日

            try
            {
                TypeSumFrationBll typesumfration = new TypeSumFrationBll();
                string TimeTamp = MyInfo.TimeTamp();
                string studentID = MyInfo.MystudentID();
                //txtMsg.Text += "\r\nIE开始判分...."
                IEQuestionEntity ieinfo = new IEQuestionEntity();
                ieinfo.paperType = MyInfo.MyPaperType();
                IEQuestionFlag iequestionflag = new IEQuestionFlag();
                iequestionflag.SwitchQuestionFlag(ieinfo);
                IeQuestionEntityBll question = new IeQuestionEntityBll();
                IEQuestionRecordEntity ierecored = new IEQuestionRecordEntity();
                ierecored.studentID = MyInfo.MystudentID();

                question.ReturnScore(IELoadInfo.list, ierecored);
                //计算PPT题型总分-王荣晓-2015年11月30日
                typesumfration.IESumFration(studentID, TimeTamp);
                //txtMsg.Text += "\r\nIE判分成功！"
                IENum = 1;
            }
            catch (Exception em)
            {
                logInfo.ieInfo = "ie错误" + em.Message;
            }
            #endregion
        }

        private void ExcelThread()
        {
            #region Excel判分 2015年11月23日
            try
            {
                TypeSumFrationBll typesumfration = new TypeSumFrationBll();
                string TimeTamp = MyInfo.TimeTamp();
                string studentID = MyInfo.MystudentID();
                //txtMsg.Text += "\r\nExcel开始判分......"
                ExcelQuestionEntity excelinfo = new ExcelQuestionEntity();
                ExcelJudgeHelper excelhelper = new ExcelJudgeHelper();
                ExcelQuestionRecordEntity excelrecored = new ExcelQuestionRecordEntity();
                ExcelEntityBll Excelquestionbll = new ExcelEntityBll();

                excelhelper.SelectJudge(excelinfo);
                excelrecored.StudentID = MyInfo.MystudentID();
                Thread.Sleep(200);
                Excelquestionbll.ReturnExcelScore(ExcelLoading.list, excelrecored);
                //计算Excel题型总分-王荣晓-2015年11月30日
                typesumfration.ExcelSumFration(studentID, TimeTamp);
                ExcelNum = 1;
            }
            catch (Exception em)
            {
                //MessageBox.Show("excel错误")
                logInfo.excelInfo = "excel错误" + em.Message;
            }

            #endregion
        }
        #endregion

        #region Word题型判分逻辑 -2018年5月2日21:11:01 修改人：李金颖-修改备注-2018-12-21 10:50:13
        /// <summary>
        /// word判分
        /// </summary>
        /// <param name="paperType"></param>
        /// <param name="student"></param>
        /// <param name="wordquestionbll"></param>
        /// <param name="wordinfo"></param>
        /// <param name="dt"></param>
        private void JudgeWord(string paperType, WordQuestionRecordEntity student, WordQuestionEntityBll wordquestionbll, WordQuestionEntity wordinfo, DataTable dt)
        {
            //判断表格C是否存在
            string filePath = string.Format("D:\\" + MyInfo.MystudentID() + "\\计算机一级考生文件\\" + paperType + "卷\\Wordkt\\bg" + paperType + ".docx");
            string fileword = string.Format("D:\\" + MyInfo.MystudentID() + "\\计算机一级考生文件\\" + paperType + "卷\\Wordkt\\Word" + paperType + ".docx");


            WordAQuestionFlag WordFlag = null;
            WordFlag = new WordAQuestionFlag();

            if (MyInfo.exitsDoc(fileword))            // 判断此路径下是否有word文件
            {
                WordFlag.SwitchQuestionFlag(wordinfo, dt);
            }
            else if (MyInfo.exitsDoc(filePath))            // 判断此路径下是否有文件
            {
                WordFlag.SwitchQuestionFlag(wordinfo, dt);
            }
            else
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    WordQuestionRecordEntity Student = new WordQuestionRecordEntity();
                    Student.StudentID = FrmLogin.studentID;
                    Student.PaperType = MyInfo.MyPaperType();
                    Student.TimeStamp = MyInfo.TimeTamp();
                    Student.QuestionID = Convert.ToDouble(dt.Rows[i]["QuestionID"]);
                    Student.ExamAnswer = "本地无考生文件";
                    Student.Fration = "0";
                    WordLoadinfo.list.Add(Student);
                }

            }
            #region Word若未修改，则判0分--刁琳童--2018年12月6日 修改人：李金颖-完善功能，注释该方法-2018-12-21 08:28:13
            //如果word文件的修改时间在考试开始时间之后，word判分直接为0--刁琳童--2018年12月6日
            ////加如此处原因：word题即使不做，也会给分，所以需要加上时间判断修改时间是否在考试时间之后


            ////获取word文件路径
            //FileInfo fi = new FileInfo(fileword);
            ////最后一次修改时间
            //DateTime fiLastWriteTime = fi.LastWriteTime;
            ////开始考试时间
            //DateTime startExamTime = Convert.ToDateTime(new StudentBindPaperTypeBLL().SelectByStudentID(student.StudentID).Rows[0]["TimeTamp"]);
            ////判断如果文件最后修改时间在考试时间之前，word判分直接清零            
            //if (fiLastWriteTime<startExamTime)
            //{
            //    for (int i = 0; i < dt.Rows.Count; i++)
            //    {
            //        WordLoadinfo.list[i].Fration = "0";
            //    }
            //}

            #endregion
            wordquestionbll.ReturnScore(WordLoadinfo.list, student);
        }
        #endregion

        #region 判断考试模式 修改人：李金颖-添加备注-2018-12-21 10:49:40
        /// <summary> 
        /// 异步完成-学生端系统设置部署
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DataTable dt = new LogBll().QuerySetUpBll();
            //上传考生文件——“0”上传
            if (dt.Rows[0]["is_upload"].ToString() == "0" && !UploadFile())
            {
                UpdateIsUse(2);//上传失败IsUse改成2
            }
            else
            {
                UpdateIsUse(0);//交卷IsUse改成0
            }
            //显示成绩——"1'为显示成绩，“0”为不显示
            if (dt.Rows[0]["is_showScore"].ToString() == "1")
            {
                ShowScore();
            }
            //锁屏——"0"为锁屏
            if (dt.Rows[0]["is_lockScreen"].ToString() == "0")
            {
                frmWaitLock frmLock = new frmWaitLock();
                frmLock.Show();
                Close();
                return;
            }
            Application.Exit();
        }
        #endregion

        #region Kill()-杀掉所有进程
        /// <summary>
        /// 杀掉所有进程
        /// </summary>
        public void Kill()
        {
            //杀txt
            foreach (Process txt in Process.GetProcessesByName("notepad"))
            {
                txt.Kill();
            }
            //杀Word
            foreach (Process word in Process.GetProcessesByName("WINWORD"))
            {
                word.Kill();
            }
            //杀Excel
            foreach (Process excel in Process.GetProcessesByName("EXCEL"))
            {
                excel.Kill();
            }

            //杀图片
            foreach (Process acdsee5 in Process.GetProcessesByName("ACDSee5"))
            {
                acdsee5.Kill();
            }

            //杀PPT
            foreach (Process ppt in Process.GetProcessesByName("POWERPNT"))
            {
                ppt.Kill();
            }
            //杀图片
            foreach (Process dllhost in Process.GetProcessesByName("dllhost"))
            {
                dllhost.Kill();
            }
            //杀图片
            foreach (Process mspaint in Process.GetProcessesByName("mspaint"))
            {
                mspaint.Kill();
            }
            //杀图片
            foreach (Process Photoshop in Process.GetProcessesByName("Photoshop"))
            {
                Photoshop.Kill();
            }
            //杀图片
            foreach (Process OIS in Process.GetProcessesByName("OIS"))
            {
                OIS.Kill();
            }
            //杀IE
            foreach (Process iexplore in Process.GetProcessesByName("iexplore"))
            {
                iexplore.Kill();
            }
        }
        #endregion

        #region 窗体加载
        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmJudge_Load(object sender, EventArgs e)
        {
            worker.RunWorkerAsync();
            //显示进度窗体 
            frmWaitting frm = new frmWaitting(worker, "正在判分，请勿动窗体，有秩序离开。。。。");
            frm.StartPosition = FormStartPosition.CenterScreen;
            frm.ShowDialog(this);

        } 
        #endregion

        #region 学生端系统设置-姜晶-2018年3月31日

        #region 练习模式下弹框显示考生成绩
        /// <summary>
        /// 显示成绩
        /// </summary>
        void ShowScore()
        {
            StudentInfoEntity studentinfoEntity = new StudentInfoEntity();
            //获取学生姓名
            studentinfoEntity.studentName = LoginEntity.studentName;
            //获取学号
            studentinfoEntity.studentID = LoginEntity.studentID;
            //根据学号查询学院代码和专业
            StudentInfoEntityBLL studentinfobll = new StudentInfoEntityBLL();
            DataTable studentinfo = studentinfobll.SelectStudentInfoByID(studentinfoEntity);
            studentinfoEntity.major = studentinfo.Rows[0]["major"].ToString();
            studentinfoEntity.CollegeID = studentinfo.Rows[0]["CollegeID"].ToString();
            //在视图View_Score中获取最近一次的成绩
            StudentScoreBLL studentscorebll = new StudentScoreBLL();
            DataTable studentscore = studentscorebll.SelectScore(studentinfoEntity);
            #region 学生端系统设置-苑仁杰-2018年12月20日
            //显示分析数据窗体       
            
            #region 加个判断，练习模式下运行Test窗体——薛帅行——2018年12月25号14点16分
            LogBll logbll = new LogBll();
            DataTable dt = new DataTable();
            dt = logbll.QuerySetUpBll();
            if (Convert.ToString(dt.Rows[0]["is_exam"]) == "1")
            {
                //Test test = new Test();
            }
            else
            {

            }
            #endregion


            //test.Show();  //不让Test显示出来


            #endregion
            //MessageBox.Show(string.Format("尊敬的{0}同学，　　\n您本次考试成绩:{1}分", studentinfoEntity.studentName, studentscore.Rows[0][0].ToString()), "考试成绩");
            //注释提示框——薛帅行——2018年12月22日14:46:46
        }
        #endregion

        #region 上传考生答题文件
        /// <summary>
        /// 上传考生答题文件
        /// </summary>
        /// <returns>true为上传成功，false为失败</returns>
        bool UploadFile()
        {
            bool flag = false;
            Regex re = new Regex("(\\d{11})", RegexOptions.None);
            string s = Regex.Replace(MyInfo.TimeTamp(), @"[^\d]*", "");
            //压缩考生答题文件
            ZipHelper.CreateZip(string.Format("D:\\" + MyInfo.MystudentID()), string.Format("D:\\" + MyInfo.MystudentID() + ".zip"));
            try
            {
                //声明一个实例
                MongoHelper mh = new MongoHelper("NCRE3");
                //上传
                string tablename = MyInfo.MycollegeID();
                if (mh.Upload(string.Format("D:\\" + MyInfo.MystudentID() + @".zip"), MyInfo.MystudentID() + "-" + s + ".zip", tablename))
                {
                    File.Delete(string.Format("D:\\" + MyInfo.MystudentID() + @".zip"));
                    flag = true;
                }
                else
                {
                    logInfo.uploadInfo += "上传文件失败";
                }
            }
            catch (Exception a)
            {
                logInfo.uploadInfo += "上传文件失败" + a.Message;
            }
            LogBll logbll = new LogBll();
            logbll.AddLogInfo(logInfo);
            return flag;
        }
        #endregion

        #region 更改用户是否登录过的标志
        /// <summary>
        /// 更改用户是否登录过的标志
        /// </summary>
        /// <param name="IsUse">要修改的IsUse</param>
        void UpdateIsUse(int IsUse)
        {
            //StudentBindType 的IsUse属性，0未在线,1在线,2上传失败
            StudentBindPaperTypeEntity studentBin = new StudentBindPaperTypeEntity();
            studentBin.TimeTamp = MyInfo.TimeTamp();
            studentBin.StudentID = MyInfo.MystudentID();
            studentBin.IsUse = IsUse;
            StudentBindTypeEntityBll studentbll = new StudentBindTypeEntityBll();
            studentbll.UpdateStudentByIsUse(studentBin);
        }
        #endregion

        #endregion
    }
}
